import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from mysite.DataHanlder import DataHanlder
from mysite.httpUtils import httpUtils
from mysite.models import ImgData


def index(request):
    context = {}
    context["msg"] = "欢迎您访问本网站"
    return render(request, 'index.html', context)

"""
上传文件的接口
"""
@csrf_exempt
def uploadFile(request):
    if request.method == 'POST':

        file = request.FILES.get('file') # 用来获取网页上传的文件

        util = httpUtils()      # 实例化请求百度接口类 调用百度API的接口
        # 请求百度图像识别 获取结果
        res = util.sendFile(file.read())
        # print(res)
        list = res['words_result']
        # 实例化数据提取类
        hanlder = DataHanlder()
        # 获取用户名
        name = str(hanlder.getUserName(list))
        # 获取订单号
        order_no = str(hanlder.get_order_no(list))
        # 获取 出发时间数组 返回的数据大于1，证明有出发时间和到站时间
        if len(hanlder.get_time(list)) > 1:
            # 从数组中获得开始时间
            start_time = hanlder.get_time(list)[0]
            # 从数组中获取到站时间
            end_time = hanlder.get_time(list)[1]
        # 获取出发日期
        start_date = str(hanlder.get_date(list))
        # 获取车次
        car_no = str(hanlder.get_car_no(list))
        # 获取价格
        price = str(hanlder.get_price(list))
        start_point = ""
        end_point = ""
        # 获取出发站和终点站 原理和时间一样
        if len(hanlder.get_point(list)) > 1:
            start_point = hanlder.get_point(list)[0]
            end_point = hanlder.get_point(list)[1]
        print("姓名: " + name)
        print("订单号: " + order_no)
        print("时间: " + str(hanlder.get_time(list)))
        print("日期: " + start_date)
        print("车次: " + car_no)
        print("价格: " + price)
        print("起停点: " + str(hanlder.get_point(list)))
        # 实例化数据模型，并赋值
        obj = ImgData(
            name=name,
            order_no=order_no,
            start_date=start_date,
            start_time=start_time,
            end_time=end_time,
            s_point=start_point,
            e_point=end_point,
            car_no=car_no,
            price=price)
        # 存入数据库
        obj.save()
        # print("temp_top = " + str(temp_top))
        # 返回
        return HttpResponse("")


@csrf_exempt
def test(request):
    if request.method == 'POST':
        import re
        t = "32:39"
        pattern = re.search(r'^(0\d|1\d|2[0-4]):[0-5]\d$', t)

        print(pattern.group())
        return HttpResponse("Hello world ! ")
